<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2018/1/9
 * Time: 10:34
 */

namespace app\index\controller;
use think\Db;

class Open extends Common
{
    //打开省份
    public function provice(){
        return $this->fetch();
    }

    //返回省份树数据-从分区开始
    public function proviceTreeAjax(){
        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                $temp2['id'] = $vv['id'];
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    //打开省份
    public function city(){
        return $this->fetch();
    }

    //返回城市树数据-从分区开始
    public function cityTreeAjax(){
        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $temp3['id'] = $v3['id'];
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    //打开经销商
    public function jxs(){
        return $this->fetch();
    }
    //打开经销商
    public function jxs2(){
        return $this->fetch();
    }

    //打开品牌--多选
    public function brand(){
        return $this->fetch();
    }

    //打开品类--多选
    public function category(){
        return $this->fetch();
    }

    //打开品牌
    public function brand2(){
        return $this->fetch();
    }

    //返回经销商树数据-从分区开始
    public function jxsTreeAjax(){
        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $t3 = Db::table('cg_jxs')
                        ->where(array('city'=>$v3['id']))
                        ->field('id,title')
                        ->select();//查经销商
                    //查系统
                    $data5 = [];
                    foreach($t3 as $k4=>$v4){
                        $temp5 = [];
                        $temp5['name'] = $v4['title'];
                        $temp5['id'] = $v4['id'];
                        $data5[] = $temp5;
                    }

                    $temp3['children'] = $data5;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    //返回网点树数据-从分区开始
    public function netTreeAjax(){
        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $t3 = Db::table('cg_jxs')
                        ->where(array('city'=>$v3['id']))
                        ->field('id,title')
                        ->select();//查经销商
                    //查系统
                    $data5 = [];
                    foreach($t3 as $k4=>$v4){
                        $temp5 = [];
                        $temp5['name'] = $v4['title'];
                        $t4 = db('cg_system')
                            ->where([
                                'jxs'=>$v4['id']
                            ])
                            ->field('id,title')
                            ->select();//查系统

                        $data6 = [];
                        foreach($t4 as $t4_k =>$t4_v){
                            $temp6 = [];
                            $temp6['name'] = $t4_v['title'];
                            $t5 = db('cg_net')
                                ->where(['system_id'=>$t4_v['id']])
                                ->field('id,title,iskey')
                                ->select();//查网点
                            $data7 = [];
                            foreach ($t5 as $t5_k=>$t5_v){
                                $temp7 = [];
                                $temp7['name'] = $t5_v['title'];
                                $temp7['id'] = $t5_v['id'];
                                if($t5_v['iskey']==1){
                                    $temp7['checked'] = true;
                                }
                                $data7[] = $temp7;
                            }
                            $temp6['children'] = $data7;
                            $temp6["chkDisabled"]=true;
                            $temp6["nocheck"]=true;
                            $data6[] = $temp6;
                        }
//                        echo db('cg_net')->getLastSql();
                        $temp5['children'] = $data6;
                        $temp5["chkDisabled"]=true;
                        $temp5["nocheck"]=true;
                        $data5[] = $temp5;
                    }

                    $temp3['children'] = $data5;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    //产品单选
    public function product2(){
        return $this->fetch();
    }
    //网点-多选
    public function net(){
        return $this->fetch();
    }
    //网点-单选
    public function net2(){
        return $this->fetch();
    }
    //产品树-从品牌开始--销售订单专用
    public function productTreeAll(){
        $jxs_id = $this->request->param('jxs_id');
        if(!$jxs_id){ //没选择经销商返回false
            return false;
        }
        //查询产品订购设置
        $dgsz = db('system_param')->where(['t'=>0,'k'=>'dingDanListType'])->value('v');

        //根据经销商查询分组
        $group_id = db('price_group_jxs')->where('jid',$jxs_id)->column('gid');

        //查询经销商对应的渠道类型
        $qdlx = db('cg_jxs')->where('id',$jxs_id)->value('channeltype');

        $brands = db('pro_brands')
            ->field('id,brand_name name')
            ->select();
        foreach($brands as $k=>$v){
            $category = Db::table('pro_category')
                ->field('id,category_name name')
                ->where('brand_id',$v['id'])
                ->select();
            foreach($category as $c_k=>$c_v){
                $series = Db::table('pro_series')
                    ->field('id,series_name name')
                    ->where('category_id',$c_v['id'])
                    ->select();
                foreach($series as $s_k=>$s_v){
                    $sku = Db::table('pro_sku')
                        ->field('id,sku_name name')
                        ->where('series_id',$s_v['id'])
                        ->select();
                    foreach($sku as $sku_k=>$sku_v){

                        $where = [];
                        $where['sku_id'] = $sku_v['id'];
                        if($dgsz==2){ //经销商对应的产品价格分组中的产品
                            $pids = db('price_group_product')
                                ->where([
                                    'gid'=>['in',$group_id],
                                ])
                                ->column('pid');
                            $where['id'] = ['in',$pids];
                        }elseif($dgsz==1){ //经销商对应渠道类型的产品

                            $where['channel_type'] = $qdlx;
                        }
                        $product = Db::table('pro_products')
                            ->field('id,pro_name name,unit,pro_no')
                            ->where($where)
                            ->select();
                        foreach($product as $p_k=>$p_v){
                            if($dgsz==2){ //下单的时候只能选择该经销商所对应的产品价格分组内的产品。
                                $price = db('price_group_product')
                                    ->where([
                                        'gid'=>['in',$group_id],
                                        'pid'=>$p_v['id'],
                                        'start_time'=>['<=',date('Y-m-d')],
                                        'end_time'=>['>=',date('Y-m-d')]
                                    ])
                                    ->field('lingshou_price,fayun_price')->find();
                                    $p_v['lingshou_price'] = $price['lingshou_price'];

                            }else{ //如果下单的产品在该经销商对应的价格分组中有价格，就遵循价格分组的价格。如果没有，则按照产品的标准出厂价
                                $price = db('price_group_product')
                                    ->where([
                                        'gid'=>['in',$group_id],
                                        'pid'=>$p_v['id'],
                                        'start_time'=>['<=',date('Y-m-d')],
                                        'end_time'=>['>=',date('Y-m-d')]
                                    ])
                                    ->field('lingshou_price,fayun_price')->find();
                                if($price){
                                    $p_v['lingshou_price'] = $price['lingshou_price'];
                                }else{
                                    //查询产品标准价格
                                    $bzj = db('pro_price')->where('pid',$p_v['id'])->value('factory');
                                    $p_v['lingshou_price'] = $bzj;
                                }
                            }

                            $product[$p_k] = $p_v;
//            $v['ygj'] = db('')
                        }
                        $sku_v['children'] = $product;
                        $sku_v["chkDisabled"] = true;
                        $sku_v["nocheck"] = true;
                        $sku[$sku_k] = $sku_v;
                    }
                    $s_v['children'] = $sku;
                    $s_v["chkDisabled"] = true;
                    $s_v["nocheck"] = true;
                    $series[$s_k] = $s_v;
                }
                $c_v['children'] = $series;
                $c_v["chkDisabled"] = true;
                $c_v["nocheck"] = true;
                $category[$c_k] = $c_v;
            }
            $v['children'] = $category;
            $v["chkDisabled"] = true;
            $v["nocheck"] = true;
            $brands[$k] = $v;
        }

        echo json_encode($brands);
    }

    //物料
    public function material2(){
        return $this->fetch();
    }

    public function materialTree(){
        $jxs_id = $this->request->param('jxs_id');

        if(!$jxs_id){ //没选择经销商返回false
            return false;
        }

        $where = [];
        $where['m_type'] = 2;

        $data = db('pro_materials')->field('id,material_name name,material_no pro_no,unit,factory lingshou_price')->where($where)->select();
        echo json_encode($data);
    }

    //人员单选
    public function employee2(){
        return $this->fetch();
    }
    //人员多选
    public function employee(){
        return $this->fetch();
    }
    //查询员工列表
    public function getem(){
        $departs=Db::table("department")->where(["is_actived"=>1,"is_deleted"=>0])
            ->field("id,parent_id as pId,de_name as name")->select();
        $employees=Db::table("employee")->alias("e")
            ->join("department_employee de","e.id=de.employee_id")
            ->join("department d","de.department_id=d.id")
            ->where(["e.is_actived"=>1,"d.is_actived"=>1,"e.is_deleted"=>0,"d.is_deleted"=>0,"de.index"=>1])
            ->field("e.id as id,d.id as pId,e.em_name as name")
            ->select();
        $result=[];
        for($i=0;$i<count($departs);$i++){
            $result[$i]["id"]=$departs[$i]["id"];
            $result[$i]["pId"]=$departs[$i]["pId"];
            $result[$i]["name"]=$departs[$i]["name"];

            $result[$i]["chkDisabled"]=true;
            $result[$i]["nocheck"]=true;
            // $result[$i]["icon"]=ROOT_PATH."/public/static/zTreeStyle/img/diy/1_close.png";
        }

        for($i=0;$i<count($employees);$i++){
            $result[$i+count($departs)]["eid"]=$employees[$i]["id"];
            $result[$i+count($departs)]["pId"]=$employees[$i]["pId"];
            $result[$i+count($departs)]["name"]=$employees[$i]["name"];
            $result[$i+count($departs)]["pname"]=db('department')->where('id',$employees[$i]["pId"])->value('de_name');
            //$result[$i+count($departs)]["icon"]="./../../static/zTreeStyle/img/diy/3.png";
        }
        return json_encode($result);
    }

    //核销单明细编号--销售订单补货
    public function hxdmxbh2(){
        return $this->fetch();
    }

    //获取核销单明细--销售订单补货
    public function gethxdmx(){
        $jxs_id = $this->request->param('jxs_id');
        if(!$jxs_id){
            return false;
        }
        $cs = db('system_param')->where(['t'=>0,'k'=>'buHuoHeXiaoDanFanWei'])->value('v');
        $where = [];
        if($cs===0){
            $where['id'] = ['in','select hx_id from cg_ti_hexiao_list where zhifufangshi=13'];
        }
        $where['jxs_id'] = $jxs_id;
        $data = db('cg_ti_hexiao')->where($where)->field('id,sn')->select();

        foreach($data as $k=>$v){
            $where2 = [];
            $where2['hx_id'] = $v['id'];
            if($cs===0){
                $where2['t.zhifufangshi'] = 13;
            }
            $v['hxje'] = round(db('cg_ti_hexiao_list')->where($where2)->sum('shijitourujine'),2);
            $v['name'] = $v['sn'];
            $data[$k]=$v;
        }
        return json_encode($data);
    }

    //核销单编号--销售订单补费
    public function hxdbh2(){
        return $this->fetch();
    }

    //获取核销单明细
    public function gethxd(){
        $jxs_id = $this->request->param('jxs_id');
        if(!$jxs_id){
            return false;
        }
        $where['jxs_id'] = $jxs_id;
        $data = db('cg_ti_hexiao')
            ->field('id,sn name,sn')
            ->where($where)
            ->select();
//        echo db('cg_ti')->getLastSql();
        foreach($data as $k=>$v){
            $zhxje = db('cg_ti_hexiao_list')->where(['hx_id'=>$v['id']])->sum('shijitourujine');
            $yzf = db('cg_ti_hexiao_zhifu')->where(['hx_id'=>$v['id']])->sum('bczfje');
            $ybf = db('cg_order_list')->where(['hxdmxbh'=>$v['id']])->sum('bfje');
            $v['hxje'] = round($zhxje-$yzf-$ybf,2);//需补费的核销金额
            $data[$k]=$v;
        }
        return json_encode($data);
    }

    //打开渠道优惠政策
    public function yhpolicy(){
        return $this->fetch();
    }
    //打开渠道优惠政策
    public function yhpolicydata(){
         $jxs_id = $this->request->param('jxs_id');
        $city = db('cg_jxs')->where('id',$jxs_id)->value('city');
        $provice = db('cg_jxs')->where('id',$jxs_id)->value('provice');
        $zoning = db('cg_jxs')->where('id',$jxs_id)->value('zoning');
        //查询是否有渠道优惠政策
        $time = date('Y-m-d');
        $where="t.status=7 and t.is_revoke is null and ((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and td.start<='{$time}' and td.end>='{$time}'";
        $qdyhzc = db('cg_channel_preferential_policy t')->join("cg_channel_preferential_policy_cxfa td","td.p_id=t.id")
            ->where($where)->field('t.id,t.title,t.sn')->group("t.id")
            ->select();
        $data=[];
        foreach ($qdyhzc as $k => $v) {
            # code...
            $mingxi=db("cg_channel_preferential_policy_cxfa")->where("((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and start<='{$time}' and end>='{$time}' and p_id={$v["id"]}")->select();

            foreach ($mingxi as $km => $vm) {
                # code...
                $deid=db("cg_channel_preferential_policy_cxfa")->where("p_id={$v["id"]} and id<={$vm["id"]}")->count();
                $tmp["id"]=$vm["id"];
                $tmp["name"]=$v["title"].'-促销方案'.$deid;
                $data[]=$tmp;

            }
        }
        echo json_encode($data);
    }

    //人员单选
    public function users2(){
        return $this->fetch();
    }

    //查询员工列表
    public function getuers(){
        $result = db('users')->field('id,login_name name')->select();
        return json_encode($result);
    }

    //返回品牌数
    public function brandsTree(){
        $data = Db::table('pro_brands')->field('id,brand_name name')->select();
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['name'];
            $temp['id'] = $v['id'];
            $temp["chkDisabled"]=false;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    //返回品类树-根据指定品牌
    public function categoryTree(){
        $data = $this->request->get('keyword');
        $where = [];
        if($data){
            $where['brand_id'] = ['in',$data];
        }
        $data = Db::table('pro_category')->field('id,category_name name')->where($where)->select();
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['name'];
            $temp['id'] = $v['id'];
            $temp["chkDisabled"]=false;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    //授权区域
    public function sqqy(){
        return $this->fetch();
    }

    //授权区域树
    public function sqqyTree(){
        $data = db('cg_provice')->field('id,title name')->select();
        foreach($data as $k=>$v){
            $city = db('cg_city')->where('provice',$v['id'])->field('id,title name')->select();
            foreach($city as $k1=>$v1){
                $v1['children'] = db('cg_county')->where('city',$v1['id'])->field('id,title name')->select();
                $city[$k1] = $v1;
            }
            $v['children'] = $city;
            $data[$k] = $v;
        }
        echo json_encode($data);
    }

    //系列
    public function series(){
        return $this->fetch();
    }

    //系列树-从品牌开始
    public function seriesTreeAll(){

        $brands = db('pro_brands')
            ->field('id,brand_name name')
            ->select();
        foreach($brands as $k=>$v){
            $category = Db::table('pro_category')
                ->field('id,category_name name')
                ->where('brand_id',$v['id'])
                ->select();
            foreach($category as $c_k=>$c_v){
                $series = Db::table('pro_series')
                    ->field('id,series_name name')
                    ->where('category_id',$c_v['id'])
                    ->select();
                $category[$c_k]["chkDisabled"]=true;
                $category[$c_k]['children'] = $series;
            }
            $brands[$k]["chkDisabled"]=true;
            $brands[$k]['children'] = $category;
        }

        echo json_encode($brands);
    }

    //sku
    public function sku(){
        return $this->fetch();
    }

    //sku树-从品牌开始
    public function skuTreeAll(){

        $brands = db('pro_brands')
            ->field('id,brand_name name')
            ->select();
        foreach($brands as $k=>$v){
            $category = Db::table('pro_category')
                ->field('id,category_name name')
                ->where('brand_id',$v['id'])
                ->select();
            foreach($category as $c_k=>$c_v){
                $series = Db::table('pro_series')
                    ->field('id,series_name name')
                    ->where('category_id',$c_v['id'])
                    ->select();
                foreach($series as $s_k=>$s_v){
                    $sku = Db::table('pro_sku')
                        ->field('id,sku_name name')
                        ->where('series_id',$s_v['id'])
                        ->select();
                    $series[$s_k]["chkDisabled"]=true;
                    $series[$s_k]['children'] = $sku;
                }
                $category[$c_k]["chkDisabled"]=true;
                $category[$c_k]['children'] = $series;
            }
            $brands[$k]["chkDisabled"]=true;
            $brands[$k]['children'] = $category;
        }

        echo json_encode($brands);
    }

    //产品
    public function product(){
        return $this->fetch();
    }
    //产品-单选
    public function product3(){
        return $this->fetch();
    }

    //ztree产品树
    public function productTree(){
        $where = [];
        $keyword = $this->request->param('keyword');
        if($keyword){
            $series = Db::table('pro_series')->where('category_id',$keyword)->field('id')->select();
            foreach($series as $k=>$v){
                $series[$k] = $v['id'];
            }
            $series = implode(',',$series);
            $sku = Db::table('pro_sku')->where('category_id',$series)->field('id')->select();
            foreach($sku as $k=>$v){
                $sku[$k] = $v['id'];
            }
            $sku = implode(',',$sku);

            $where['sku_id'] = ['in',$sku];
        }
        $data = Db::table('pro_products')
            ->field('id,pro_name name,pro_no,unit')
            ->where($where)
            ->select();
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['name'];
            $temp['id'] = $v['id'];
            $temp["chkDisabled"]=false;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }
    //费用计入部门树
    public function jrbmtree(){
        $data = Db::table('cg_fijiruzd t')->join('department t2','t2.id=t.title')->field('t2.de_name name,t2.id')->select();
        echo json_encode($data);
    }


}